#!/bin/bash
# 应用更新脚本

# 配置文件路径（存储Gitee凭证）
CONFIG_FILE="/var/www/git_credentials.conf"

# 如果配置文件不存在，则创建并提示用户输入凭证
if [ ! -f "$CONFIG_FILE" ]; then
    echo "未找到Git凭证配置文件，请输入Gitee账号信息（将保存在 $CONFIG_FILE）"
    read -p "Gitee用户名: " GITEE_USERNAME
    read -s -p "Gitee密码: " GITEE_PASSWORD
    echo
    echo "# Gitee凭证配置" > "$CONFIG_FILE"
    echo "GITEE_USERNAME=\"$GITEE_USERNAME\"" >> "$CONFIG_FILE"
    echo "GITEE_PASSWORD=\"$GITEE_PASSWORD\"" >> "$CONFIG_FILE"
    chmod 600 "$CONFIG_FILE"  # 设置权限，只有拥有者可读写
    echo "凭证已保存到 $CONFIG_FILE"
fi

# 读取配置文件
source "$CONFIG_FILE"

# 切换到项目目录
cd /var/www/App-Framework-Analyzer

# 配置Git凭证
git config --local credential.helper store
echo "https://$GITEE_USERNAME:$GITEE_PASSWORD@gitee.com" > ~/.git-credentials
chmod 600 ~/.git-credentials

# 拉取最新代码
echo "正在拉取最新代码..."
git pull

# 清理凭证（安全措施）
rm -f ~/.git-credentials
git config --local --unset credential.helper

# 更新后端依赖
echo "正在更新后端依赖..."
source venv/bin/activate
pip install -r requirements.txt
deactivate

# 更新前端依赖并构建
echo "正在更新前端依赖并构建..."
cd app/frontend
npm install
npm run build:prod

# 重启服务
echo "正在重启服务..."
sudo systemctl restart app-framework-analyzer-api
sudo systemctl restart app-framework-analyzer-front

# 检查服务状态
echo "检查服务状态..."
sudo systemctl status app-framework-analyzer-api --no-pager
sudo systemctl status app-framework-analyzer-front --no-pager

echo "「应用框架分析器」更新完成！"
echo "更新时间: $(date)"